package service

import (
	"errors"
	"perfect-vue-admin/global"
	"perfect-vue-admin/model"
	"perfect-vue-admin/model/request"
	"perfect-vue-admin/utils"

	uuid "github.com/satori/go.uuid"
	"gorm.io/gorm"
)

// @title    Register
// @description   register, 用户注册
// @auth                     （2020/04/05  20:22）
// @param     u               model.SysUser
// @return    err             error
// @return    userInter       *SysUser

func Register(u model.SysUser) (err error, userInter model.SysUser) {
	var user model.SysUser
	if !errors.Is(global.DB.Where("username = ?", u.Username).First(&user).Error, gorm.ErrRecordNotFound) { // 判断用户名是否注册
		return errors.New("用户名已注册"), userInter
	}
	// 否则 附加uuid 密码md5简单加密 注册
	if u.Password != "" {
		u.Password = utils.MD5V([]byte(u.Password))
	} else {
		u.Password = utils.MD5V([]byte("000000"))
	}
	if u.HeaderImg == "" {
		u.HeaderImg = "/static/upload/avatar/default.png"
	}
	u.UUID = uuid.NewV4()
	err = global.DB.Create(&u).Error
	return err, u
}

// @title    Login
// @description   login, 用户登录
// @auth                     （2020/04/05  20:22）
// @param     u               *model.SysUser
// @return    err             error
// @return    userInter       *SysUser

func Login(u *model.SysUser) (err error, userInter *model.SysUser) {
	var user model.SysUser
	u.Password = utils.MD5V([]byte(u.Password))
	err = global.DB.Where("username = ? AND password = ?", u.Username, u.Password).Preload("Authority").First(&user).Error
	return err, &user
}

// @title    ChangePassword
// @description   change the password of a certain user, 修改用户密码
// @auth                     （2020/04/05  20:22）
// @param     u               *model.SysUser
// @param     newPassword     string
// @return    err             error
// @return    userInter       *SysUser

func ChangePassword(u *model.SysUser, newPassword string) (err error, userInter *model.SysUser) {
	var user model.SysUser
	u.Password = utils.MD5V([]byte(u.Password))
	err = global.DB.Where("username = ? AND password = ?", u.Username, u.Password).First(&user).Update("password", utils.MD5V([]byte(newPassword))).Error
	return err, u
}

// @title    GetInfoList
// @description   get user list by pagination, 分页获取数据
// @auth                      （2020/04/05  20:22）
// @param     info             request.PageInfo
// @return    err              error
// @return    list             interface{}
// @return    total            int

func GetUserInfoList(info request.PageInfo) (err error, userList []model.SysUser, total int64) {
	table := global.DB.Model(&model.SysUser{})
	if info.Keyword != "" && info.Query != "" {
		table = table.Where(info.Keyword+" = ?", info.Query)
	}
	if info.UserState == 0 || info.UserState == 1 {
		table = table.Where("state = ?", info.UserState)
	}
	if info.SortColumn != "" && info.Order != "" {
		table = table.Order(info.SortColumn + " " + info.Order)
	}
	table.Count(&total)
	if info.Page == -1 && info.PageSize == -1 {
		err = table.Preload("Authority").Find(&userList).Error
	}else {
		err = table.Limit(info.PageSize).Offset((info.Page - 1) * info.PageSize).Preload("Authority").Find(&userList).Error
	}
	return err, userList, total
}

func GetUserListByIds(Ids []int) (userList []model.SysUser, err error) {
	err = global.DB.Find(&userList, Ids).Preload("Authority").Error
	return
}

// @title    SetUserAuthority
// @description   set the authority of a certain user, 设置一个用户的权限
// @auth                     （2020/04/05  20:22）
// @param     uuid            UUID
// @param     authorityId     string
// @return    err             error

func SetUserAuthority(uuid uuid.UUID, authorityId string) (err error) {
	err = global.DB.Where("uuid = ?", uuid).First(&model.SysUser{}).Update("authority_id", authorityId).Error
	return err
}

// @title    SetUserAuthority
// @description   set the authority of a certain user, 设置一个用户的权限
// @auth                     （2020/04/05  20:22）
// @param     uuid            UUID
// @param     authorityId     string
// @return    err             error

func DeleteUser(id float64) (err error) {
	var user model.SysUser
	err = global.DB.Where("id = ?", id).Delete(&user).Error
	return err
}

// @title    SetUserInfo
// @description   set the authority of a certain user, 设置用户信息
// @auth                     （2020/04/05  20:22）
// @param     uuid            UUID
// @param     authorityId     string
// @return    err             error

func SetUserInfo(reqUser model.SysUser) (err error, user model.SysUser) {
	err = global.DB.Model(&model.SysUser{}).Where("id = ?", reqUser.ID).Updates(reqUser).Error
	return err, reqUser
}

func ChangeUserState(user request.StateForm) error {
	return global.DB.Model(&model.SysUser{}).Where("id = ?", user.ID).Update("state", user.State).Error
}

func BatchDeleteUsers(ids []int) (error error) {
	return global.DB.Delete(&model.SysUser{}, ids).Error
}

func CleanUsers() (err error) {
	return global.DB.Where("1 = 1").Delete(&model.SysUser{}).Error
}

func GetUserById(id uint) (err error, user model.SysUser)  {
	err = global.DB.First(&user, id).Error
	return
}